<?php
session_start();

// 检查并初始化文件
function ensureFile($filename, $defaultContent = '[]') {
    if (!file_exists($filename)) {
        file_put_contents($filename, $defaultContent);
    }
    $content = file_get_contents($filename);
    $data = json_decode($content, true);
    return is_array($data) ? $data : json_decode($defaultContent, true);
}

// 当前用户
$currentUser = $_SESSION['username'] ?? null;
if (!$currentUser) {
    header('Location: login.php');
    exit();
}

// 文件路径
$messagesFile = __DIR__ . '/messages/system_messages.json';
$ffile = __DIR__ . '/ffile.json';
$userChatsFile = __DIR__ . "/user/$currentUser/chats.json";

// 初始化文件
$messages = ensureFile($messagesFile);
$friendConfig = ensureFile($ffile);

// 确保好友配置文件存在且格式正确
if (!isset($friendConfig[$currentUser])) {
    $friendConfig[$currentUser] = [];
}
file_put_contents($ffile, json_encode($friendConfig));

// 处理好友请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'], $_POST['from_user'])) {
    $action = $_POST['action'];
    $fromUser = $_POST['from_user'];

    foreach ($messages as $key => $message) {
        if ($message['type'] === 'friend_request' && $message['to_user'] === $currentUser && $message['from_user'] === $fromUser) {
            if ($action === 'accept') {
                // 更新 ffile.json，建立双向好友关系
                if (!isset($friendConfig[$fromUser])) {
                    $friendConfig[$fromUser] = [];
                }

                if (!in_array($fromUser, $friendConfig[$currentUser])) {
                    $friendConfig[$currentUser][] = $fromUser;
                }
                if (!in_array($currentUser, $friendConfig[$fromUser])) {
                    $friendConfig[$fromUser][] = $currentUser;
                }

                file_put_contents($ffile, json_encode($friendConfig));

                // 更新用户的 chats.json 文件
                $fromUserChatsFile = __DIR__ . "/user/$fromUser/chats.json";
                $fromUserChats = ensureFile($fromUserChatsFile);

                $chatId = md5($currentUser . $fromUser);

                // 当前用户的 chats.json
                $currentChats = ensureFile($userChatsFile);
                $currentChats[] = [
                    'id' => $fromUser,
                    'name' => $fromUser,
                    'type' => 'private'
                ];

                // 对方用户的 chats.json
                $fromUserChats[] = [
                    'id' => $currentUser,
                    'name' => $currentUser,
                    'type' => 'private'
                ];

                file_put_contents($userChatsFile, json_encode($currentChats));
                file_put_contents($fromUserChatsFile, json_encode($fromUserChats));

                // 发送系统通知
                $messages[] = [
                    'type' => 'system_message',
                    'to_user' => $fromUser,
                    'content' => "$currentUser 已接受了你的好友请求。",
                    'timestamp' => date('Y-m-d H:i:s')
                ];
            }

            // 删除好友请求消息
            unset($messages[$key]);
            file_put_contents($messagesFile, json_encode($messages));

            // 自动跳转到主页
            header('Location: index.php');
            exit();
        }
    }
}

// 获取当前用户的好友请求
$friendRequests = array_filter($messages, function ($message) use ($currentUser) {
    return $message['to_user'] === $currentUser && $message['type'] === 'friend_request';
});
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>系统消息 - JIIL微聊</title>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #2d2d2d;
            --primary-hover: #3a56e0;
            --secondary: #6c757d;
            --light: #f8f9fa;
            --dark: #212529;
            --success: #28a745;
            --danger: #dc3545;
            --border-radius: 12px;
            --box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            --transition: all 0.3s ease;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Noto Sans SC', sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #e4edf9 100%);
            color: #2c3e50;
            line-height: 1.6;
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 800px;
            margin: 40px auto;
            background: white;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(to right, var(--primary), #5e72e4);
            color: white;
            padding: 25px 30px;
            position: relative;
        }
        
        .header h1 {
            font-size: 1.8rem;
            font-weight: 700;
            margin-bottom: 5px;
            display: flex;
            align-items: center;
        }
        
        .header h1 i {
            margin-right: 12px;
            font-size: 1.5rem;
        }
        
        .header p {
            opacity: 0.9;
            font-size: 0.95rem;
        }
        
        .notification-badge {
            position: absolute;
            top: 20px;
            right: 20px;
            background: var(--danger);
            color: white;
            border-radius: 50%;
            width: 28px;
            height: 28px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.9rem;
            font-weight: 700;
        }
        
        .content {
            padding: 30px;
        }
        
        .section-title {
            font-size: 1.4rem;
            font-weight: 700;
            color: var(--dark);
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid rgba(67, 97, 238, 0.1);
            display: flex;
            align-items: center;
        }
        
        .section-title i {
            margin-right: 10px;
            color: var(--primary);
        }
        
        .request-list {
            display: grid;
            grid-template-columns: 1fr;
            gap: 20px;
            margin-bottom: 40px;
        }
        
        .request-card {
            display: flex;
            align-items: center;
            padding: 20px;
            border-radius: var(--border-radius);
            background: var(--light);
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);
            transition: var(--transition);
            border-left: 4px solid var(--primary);
        }
        
        .request-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 7px 20px rgba(0, 0, 0, 0.1);
        }
        
        .avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: linear-gradient(to right, #4361ee, #5e72e4);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            font-weight: 700;
            margin-right: 20px;
            flex-shrink: 0;
        }
        
        .request-details {
            flex-grow: 1;
        }
        
        .request-user {
            font-size: 1.2rem;
            font-weight: 600;
            color: var(--dark);
            margin-bottom: 5px;
        }
        
        .request-message {
            color: var(--secondary);
            font-size: 0.95rem;
            margin-bottom: 15px;
        }
        
        .request-time {
            color: #6c757d;
            font-size: 0.85rem;
            display: flex;
            align-items: center;
        }
        
        .request-time i {
            margin-right: 5px;
        }
        
        .action-buttons {
            display: flex;
            gap: 10px;
        }
        
        .btn {
            padding: 8px 20px;
            border-radius: 50px;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
            border: none;
            font-size: 0.95rem;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .btn-accept {
            background: var(--success);
            color: white;
        }
        
        .btn-accept:hover {
            background: #218838;
            transform: translateY(-2px);
        }
        
        .btn-decline {
            background: var(--light);
            color: var(--secondary);
        }
        
        .btn-decline:hover {
            background: #e9ecef;
            transform: translateY(-2px);
        }
        
        .empty-state {
            text-align: center;
            padding: 50px 30px;
            background: #f8fafc;
            border-radius: var(--border-radius);
            border: 2px dashed #dee2e6;
        }
        
        .empty-icon {
            font-size: 3.5rem;
            color: #dee2e6;
            margin-bottom: 20px;
        }
        
        .empty-title {
            font-size: 1.3rem;
            font-weight: 600;
            color: #6c757d;
            margin-bottom: 10px;
        }
        
        .empty-text {
            color: #6c757d;
            max-width: 500px;
            margin: 0 auto 20px;
        }
        
        .btn-primary {
            background: var(--primary);
            color: white;
            padding: 10px 25px;
            border-radius: 50px;
            display: inline-flex;
            align-items: center;
            font-weight: 600;
            text-decoration: none;
            transition: var(--transition);
        }
        
        .btn-primary:hover {
            background: var(--primary-hover);
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(67, 97, 238, 0.3);
        }
        
        .btn-primary i {
            margin-right: 8px;
        }
        
        .footer {
            text-align: center;
            padding: 20px;
            color: #6c757d;
            font-size: 0.9rem;
            border-top: 1px solid #eaeaea;
            background: #f8fafc;
        }
        
        @media (max-width: 768px) {
            .request-card {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .avatar {
                margin-bottom: 15px;
            }
            
            .action-buttons {
                width: 100%;
                margin-top: 15px;
            }
            
            .btn {
                flex: 1;
            }
        }
        
        @media (max-width: 480px) {
            .content {
                padding: 20px 15px;
            }
            
            .header {
                padding: 20px;
            }
            
            .request-card {
                padding: 15px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-bell"></i> 系统消息中心</h1>
            <p>管理您的好友请求和系统通知</p>
            <?php if (!empty($friendRequests)): ?>
                <div class="notification-badge"><?= count($friendRequests) ?></div>
            <?php endif; ?>
        </div>
        
        <div class="content">
            <h2 class="section-title"><i class="fas fa-user-plus"></i> 好友请求</h2>
            
            <?php if (empty($friendRequests)): ?>
                <div class="empty-state">
                    <div class="empty-icon">
                        <i class="far fa-check-circle"></i>
                    </div>
                    <h3 class="empty-title">暂无好友请求</h3>
                    <p class="empty-text">您目前没有收到任何好友请求。当有人向您发送好友请求时，您将在此处收到通知。</p>
                    <a href="index.php" class="btn-primary">
                        <i class="fas fa-home"></i> 返回首页
                    </a>
                </div>
            <?php else: ?>
                <div class="request-list">
                    <?php foreach ($friendRequests as $request): ?>
                        <div class="request-card">
                            <div class="avatar">
                                <?= strtoupper(substr($request['from_user'], 0, 1)) ?>
                            </div>
                            <div class="request-details">
                                <div class="request-user"><?= htmlspecialchars($request['from_user']) ?></div>
                                <div class="request-message">请求添加您为好友</div>
                                <div class="request-time">
                                    <i class="far fa-clock"></i> <?= date('Y-m-d H:i', strtotime($request['timestamp'])) ?>
                                </div>
                            </div>
                            <form method="POST" class="action-buttons">
                                <input type="hidden" name="from_user" value="<?= htmlspecialchars($request['from_user']) ?>">
                                <button type="submit" name="action" value="accept" class="btn btn-accept">
                                    <i class="fas fa-check"></i> 接受
                                </button>
                                <button type="button" class="btn btn-decline" disabled>
                                    <i class="fas fa-times"></i> 拒绝不理会即可
                                </button>
                            </form>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
        
        <div class="footer">
            <p>© <?= date('Y') ?> 如果你无法收到好友请求，请检查是否正确发送申请</p>
        </div>
    </div>
    
    <script>
        // 添加简单的动画效果
        document.addEventListener('DOMContentLoaded', function() {
            const cards = document.querySelectorAll('.request-card');
            cards.forEach((card, index) => {
                setTimeout(() => {
                    card.style.opacity = '0';
                    card.style.transform = 'translateY(20px)';
                    card.style.transition = 'all 0.5s ease';
                    
                    setTimeout(() => {
                        card.style.opacity = '1';
                        card.style.transform = 'translateY(0)';
                    }, 50);
                }, index * 100);
            });
        });
    </script>
</body>
</html>